package com.example.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

class ConstructorTest {
    private String name;
    private int age;

    public ConstructorTest() {
    }

    public ConstructorTest(String name) {
        this.name = name;
    }

    public ConstructorTest(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "ConstructorTest{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class ConstructorTests {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取所有的构造器。如果该类没有公共构造函数，或者该类是数组类，或者该类反映原始类型或void，则返回长度为0的数组
        Constructor<?>[] constructors = ConstructorTest.class.getConstructors();

        // 输出：
        // public com.example.reflect.ConstructorTest(java.lang.String,int)
        // public com.example.reflect.ConstructorTest(java.lang.String)
        // public com.example.reflect.ConstructorTest()
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        // 根据参数列表获取指定的构造器
        // 例如这里获取只有一个String类型参数的构造器
        Constructor<ConstructorTest> constructorsWithStringParameter = ConstructorTest.class.getConstructor(String.class);
        ConstructorTest instance = constructorsWithStringParameter.newInstance("二零零二年的第一场雪");
        System.out.println(instance);
    }
}
